package eu.supersheep.dao;

import eu.supersheep.dao.HttpClient;
import eu.supersheep.dao.response.TestResponse;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.Hashtable;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.util.Log;

/**
 * @class JsonUtils
 * Klasa odpowiedzialna za przetworzenie danych z tekstu na obiekty
 * Response
 * @author Artur Gurgul
 */
public class JsonUtils {
	private static final JsonUtils sharedInstance = new JsonUtils();
	
	private JsonUtils() {
	}
	
    public static JsonUtils getInstance() {
        return sharedInstance;
    }
    
	/**
	* Przetowrzenie stringu zawierajacego json na objekty 
	* @param json
	* @param responseName
	* @return
	*/
	public Response prepare (String json, String responseName) {
		Response response = new Response();
		try {
			Class responseClass = Class.forName("eu.supersheep.dao.response."+responseName+"Response");
			Constructor responseConstructor = responseClass.getConstructor();
			response = (Response) responseConstructor.newInstance();
			HttpClient httpClient = HttpClient.getInstance();
			JSONObject responseJSON = (JSONObject) new JSONTokener(json).nextValue();
			Field fields[]  = responseClass.getDeclaredFields();

			for (Field field:fields) {
				String fieldName = field.getName();
				char[] fieldChar = fieldName.toCharArray();
				fieldChar[0] = Character.toUpperCase(fieldName.charAt(0));
				String className = new String(fieldChar);
				try {
					ArrayList<Object> list = new ArrayList<Object>();
					JSONArray fieldArray = responseJSON.getJSONArray(className);
					Class modelClass = Class.forName("eu.supersheep.dao.model."+className+"Model");
					for (int i = 0; i < fieldArray.length(); i++) {
						Object modelInstance = modelClass.newInstance();
						JSONObject modelJSON = fieldArray.getJSONObject(i);
						for (Field modelField:modelClass.getDeclaredFields()) {
							try {
								modelField.set(modelInstance,modelJSON.getString(modelField.getName()) );
							} catch (Exception e) {
								Log.e("resp",e.toString());
							}
						}
						field.set(response, list);
						list.add(modelInstance);
					}
				} catch (Exception e) {
					Log.e("resp","can not find json filed: "+e.toString());	
				}	
			}
		} catch (Exception e){
			Log.i("resp","something wrong: "+e.toString());
		}

		return response;		
	}
}
